package co.chuangdian.oflauncher.uc;

import org.json.JSONException;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import cn.onekit.CALLBACK;
import cn.onekit.CONFIG;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import co.chuangdian.oflauncher.MainActivity;
import co.chuangdian.oflauncher.R;

public class AppCard extends Dialog {
	PackageInfo app;
	EditText titleEditText;
	TextView folderTextView;
	String subTitle;
	CALLBACK<String> callback;

	public AppCard(Context context, PackageInfo app, String subTitle, CALLBACK<String> callback) {
		super(context, R.style.Dialog);
		this.app = app;
		this.subTitle = subTitle;
		this.callback = callback;
	}

	Button hideButton, deleteButton;
	ImageView iconImageView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dialog_appcard);
		iconImageView = (ImageView) this.findViewById(R.id.iconImageView);
		titleEditText = (EditText) this.findViewById(R.id.titleEditText);
		folderTextView = (TextView) this.findViewById(R.id.folderTextView);
		hideButton = (Button) this.findViewById(R.id.hideButton);
		deleteButton = (Button) this.findViewById(R.id.deleteButton);
		//
		PackageManager packageManager = getContext().getPackageManager();
		final String appID = app.packageName;
		Drawable icon = app.applicationInfo.loadIcon(packageManager);
		String title = MainActivity.getAlias(app);
		iconImageView.setImageDrawable(icon);
		titleEditText.setText(title);
		titleEditText.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_DONE) {
					try {
						String title = v.getText().toString();
						MainActivity.alias.put(appID, title);
						CONFIG.set("alias", MainActivity.alias);
						dismiss();
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				return false;
			}

		});
		folderTextView.setText(subTitle);
		hideButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				callback.run(false, appID);
				dismiss();
			}

		});
		deleteButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				callback.run(true, appID);
				dismiss();
			}
		});
	}

}
